﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;
using com.google.zxing;
using System.Text.RegularExpressions;

namespace MayhemWinPhone
{
    public partial class SettingsPage : PhoneApplicationPage
    {
        Storyboard sbErrorIPFadeOut;
        Storyboard sbErrorIPFadeIn;
        Storyboard sbErrorPortFadeOut;
        Storyboard sbErrorPortFadeIn;

        const double ErrorAnimationTime = 0.25;

        public SettingsPage()
        {
            InitializeComponent();

            sbErrorIPFadeOut = new Storyboard();
            sbErrorIPFadeOut.Duration = new Duration(TimeSpan.FromSeconds(ErrorAnimationTime));
            sbErrorIPFadeOut.Children.Add(new DoubleAnimation() { Duration = new Duration(TimeSpan.FromSeconds(ErrorAnimationTime)), To = 0 });
            Storyboard.SetTarget(sbErrorIPFadeOut, textBlockErrorIP);
            Storyboard.SetTargetProperty(sbErrorIPFadeOut, new PropertyPath("UIElement.Opacity"));

            sbErrorIPFadeIn = new Storyboard();
            sbErrorIPFadeIn.Duration = new Duration(TimeSpan.FromSeconds(ErrorAnimationTime));
            sbErrorIPFadeIn.Children.Add(new DoubleAnimation() { Duration = new Duration(TimeSpan.FromSeconds(ErrorAnimationTime)), To = 1 });
            Storyboard.SetTarget(sbErrorIPFadeIn, textBlockErrorIP);
            Storyboard.SetTargetProperty(sbErrorIPFadeIn, new PropertyPath("UIElement.Opacity"));

            sbErrorPortFadeOut = new Storyboard();
            sbErrorPortFadeOut.Duration = new Duration(TimeSpan.FromSeconds(ErrorAnimationTime));
            sbErrorPortFadeOut.Children.Add(new DoubleAnimation() { Duration = new Duration(TimeSpan.FromSeconds(ErrorAnimationTime)), To = 0 });
            Storyboard.SetTarget(sbErrorPortFadeOut, textBlockErrorPort);
            Storyboard.SetTargetProperty(sbErrorPortFadeOut, new PropertyPath("UIElement.Opacity"));

            sbErrorPortFadeIn = new Storyboard();
            sbErrorPortFadeIn.Duration = new Duration(TimeSpan.FromSeconds(ErrorAnimationTime));
            sbErrorPortFadeIn.Children.Add(new DoubleAnimation() { Duration = new Duration(TimeSpan.FromSeconds(ErrorAnimationTime)), To = 1 });
            Storyboard.SetTarget(sbErrorPortFadeIn, textBlockErrorPort);
            Storyboard.SetTargetProperty(sbErrorPortFadeIn, new PropertyPath("UIElement.Opacity"));
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/VideoPage.xaml", UriKind.RelativeOrAbsolute));

            //WP7BarcodeManager.ScanMode = BarcodeFormat.QR_CODE; //Tell barcode library what type of scan we want to perform

            //new Timer(new TimerCallback(o => Dispatcher.BeginInvoke(new Action(() =>
            //{
            //    textBlockError.Text = "Processing...";
            //    textBlockError.Foreground = new SolidColorBrush(Colors.White);
            //}))), null, 500, Timeout.Infinite);

            //WP7BarcodeManager.ScanBarcode(Barcode_Results);
        }

        /// <summary>
        /// Callback method that processes results returned by the WP7BarcodeManager. Results are also stored at WP7BarcodeManager.LastCaptureResults.
        /// </summary>
        /// <param name="BCResults">Object that holds all the results of processing the barcode. Results are also stored at WP7BarcodeManager.LastCaptureResults.</param>
        //public void Barcode_Results(WP7_Barcode_Library.BarcodeCaptureResult Results)
        //{
        //    if (Results.State == CaptureState.Success)
        //    {
        //        //     textBox1.Text = Results.BarcodeText; //Use results
        //        string[] results = Results.BarcodeText.Split(':');
        //        try
        //        {
        //            string port = results[0];
        //            string ip = results[1];
        //            textBoxIP.Text = ip;
        //            textBoxPort.Text = port;

        //            NavigationService.GoBack();
        //        }
        //        catch
        //        {
        //            textBlockError.Text = "Error scanning. Try again.";
        //            textBlockError.Foreground = new SolidColorBrush(Colors.Red);
        //        }
        //    }
        //    else //Error occured
        //    {
        //        textBlockError.Text = "Error scanning. Try again.";
        //        textBlockError.Foreground = new SolidColorBrush(Colors.Red);

        //        if (Results.BarcodeImage != null)
        //        {
        //            image1.Source = Results.BarcodeImage; //Display image
        //        }
        //        else
        //        {
        //            //No image captured
        //        }
        //    }
        //}

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
            {
                string text = VideoPage.Text;
                try
                {
					string[] results = text.Split(':');
                    string port = results[0];
                    if (results.Length > 2)
                    {
                        string ipText = results[1];
                        for (int i = 2; i < results.Length; i++)
                        {
                            ipText += ";" + results[i];
                        }
                        textBoxIP.Text = ipText;
                    }
                    else
                    {
                        string ip = results[1];
                        textBoxIP.Text = ip;
                    }
                    textBoxPort.Text = port;

                    NavigationService.GoBack();
                }
                catch
                {
                    textBlockError.Text = "Error scanning. Try again.";
                    textBlockError.Foreground = new SolidColorBrush(Colors.Red);
                }
            }
        }

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            Log.Write("OnNavigatingFrom Settings: " + textBoxIP.Text + " " + textBoxPort.Text);
            SavedData.IP = textBoxIP.Text;
            SavedData.Port = textBoxPort.Text;
            base.OnNavigatingFrom(e);
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            Log.Write("Content loaded");
            textBoxIP.Text = SavedData.IP;
            textBoxPort.Text = SavedData.Port;
        }

        bool IsValidIP(string addr)
        {
            //create our match pattern
            string pattern = @"^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
            //create our Regular Expression object
            Regex check = new Regex(pattern);
            //boolean variable to hold the status
            bool valid = false;
            //check to make sure an ip address was provided
            if (addr == "")
            {
                //no address provided so return false
                valid = false;
            }
            else
            {
                //address provided so use the IsMatch Method
                //of the Regular Expression object
                valid = check.IsMatch(addr, 0);
            }
            //return the results
            return valid;
        } 

        private void textBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                this.Focus();
        }

        private void textBoxIP_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!IsValidIP(textBoxIP.Text))
            {
                sbErrorIPFadeIn.Begin();
            }
            else
            {
                sbErrorIPFadeOut.Begin();
            }
        }

        private void textBoxPort_TextChanged(object sender, TextChangedEventArgs e)
        {
            int num;
            if (!int.TryParse(textBoxPort.Text, out num) || num < 0 || num > 65535)
            {
                sbErrorPortFadeIn.Begin();
            }
            else
            {
                sbErrorPortFadeOut.Begin();
            }
        }
    }
}